/*
 * dpd201.c
 *
 * Copyright 2023 dh33ex <dh33ex@riseup.net>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301, USA.
 *
 *
 */

#ifndef __msp430_h_
    #include <msp430.h>
#endif
#include "dpd201.h"


void VFD_init(void) {
    P1SEL = BIT2 ;                      /* P1.2 = TXD */
    P1SEL2 = BIT2;
    UCA0CTL1 |= UCSSEL_2;               /* SMCLK */
    UCA0BR0 = 104;                      /* 1MHz 9600 */
    UCA0BR1 = 0;                        /* 1MHz 9600 */
    UCA0MCTL = UCBRS0;                  /* modulation UCBRSx = 1 */
    UCA0CTL1 &= ~UCSWRST;               /* unhold reset */
}

void VFD_write(char *text) {
    unsigned short i = 0;
    do {
        while (!(IFG2 & UCA0TXIFG));    /* wait until UART is free */
        UCA0TXBUF = 255 - 2*text[i];    /* encode byte and send */
    } while (text[++i] != '\0');        /* do it until zero-symbol */
}

void VFD_clear(void) {
    char _clr[] = {0x0C, '\0'};         /* creat packet with CLR command */
    VFD_write(_clr);                    /* send this packet */
}

void VFD_brightness(unsigned char n) {
    char _data[] = {0x1F, 0x58, n, '\0'};   /* creat packet with brightness command */
    VFD_write(_data);                       /* send this packet */
}

void VFD_set_address(unsigned char x, unsigned char y) {
    char _data[] = {0x1B, 0x48, x + 20*y, '\0'};    /* creat packet with position command */
    VFD_write(_data);                               /* send this packet */
}
